﻿using GBT.Tool.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Threading;
using System.Timers;

namespace QiSiMealServiceForLinux
{
    class Program
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        private static System.Timers.Timer aTimer;
        HttpRequest hr = new HttpRequest();
        public static string host_url = "https://www.qisisw.com:8082/";

        public Program()
        {
            aTimer = new System.Timers.Timer
            {
                Interval = 501
            };

            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;

            // Have the timer fire repeated events (true is the default)
            aTimer.AutoReset = true;

            // Start the timer
            aTimer.Enabled = true;
        }

        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            if (e.SignalTime.ToString("yyyy-MM-dd HH:mm:ss") == DateTime.Now.ToString("yyyy-MM-dd") + " 15:00:00")
            {
                aTimer.Enabled = false;
                logger.Info("【" + e.SignalTime.ToString("yyyy-MM-dd HH:mm:ss") + "】: 开始执行");
                WaitCallback callback = delegate (object state) { Task(); };
                ThreadPool.QueueUserWorkItem(callback);
            }
        }

        private void Task()
        {
            try
            {
                JObject param = new JObject();
                param["districtID"] = 1;
                string requestJson = JsonConvert.SerializeObject(param);

                //调用发送报餐提醒接口
                hr.GBTPost(host_url + "gbt/MealMessage/SendMessage", requestJson);

                Thread.Sleep(1000);
                aTimer.Enabled = true;
                logger.Info("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】: 定时器重置，重新开始运行");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }

        static void Main(string[] args)
        {
            aTimer.Enabled = true;
        }
    }
}
